<!--  -->
<template>
  <div>
    <el-card class="main-card">
      <el-row>
        <el-col :span="8">
          <search :value="queryInfo.queryString" @search="querySearch"/>
        </el-col>
        <el-col :span="2">
          <el-button
            style="margin-left: 10px"
            @click="insert"
            type="primary"
            v-hasPermi="['PRE_ROLE_INSERT']"
            >添加信息</el-button
          >
        </el-col>
      </el-row>
      <el-table
        :data="tableList"
        stripe
        v-loading="loading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
      >
        <el-table-column type="index" label="序号" />
        <el-table-column prop="label" label="角色标签" />
        <el-table-column prop="code" label="角色标签值" />
        <el-table-column label="是否启用" v-hasPermi="['PRE_ROLE_UPDATE']">
          <template slot-scope="scope">
            <el-switch
              @change="updateStatus(scope.row)"
              v-model="scope.row.status"
            />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-button
              type="primary"
              @click="update(scope.row)"
              v-hasPermi="['PRE_ROLE_UPDATE']"
              size="small"
              icon="el-icon-edit"
              circle
            />
            <el-button
              type="danger"
              @click="deleteById(scope.row.id)"
              v-hasPermi="['PRE_ROLE_DELETE']"
              size="small"
              icon="el-icon-delete"
              circle
            />
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="total > 0"
        @size-change="handlePageSize"
        @current-change="handlePageNumber"
        :current-page="queryInfo.pageNumber"
        :page-sizes="[7, 15, 50, 100]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </el-card>
    <!-- 表单添加/修改 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="40%"
      @close="dialogClose"
    >
      <el-form :model="form" ref="form" :rules="rules">
        <el-row>
          <el-col :span="11">
            <el-form-item label="角色标签" prop="label">
              <el-input v-model="form.label" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="角色标签值" prop="code">
              <el-input v-model="form.code" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="23">
            <el-card>
              <div slot="header" class="clearfix">
                <span>菜单列表</span>
              </div>
              <el-tree
                ref="tree"
                check-strictly
                highlight-current
                :data="menuList"
                show-checkbox
                node-key="id"
                :props="{ label: 'title', children: 'children' }"
                @check-change="treeChange"
              />
            </el-card>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="23">
            <el-card>
              <div slot="header" class="clearfix">
                <span>权限列表</span>
              </div>
              <el-checkbox-group v-model="checkPermissions">
                <el-checkbox
                  border
                  size="small"
                  v-for="(item, index) in permissions"
                  :disabled="!item.status"
                  :label="item.label"
                  :key="index"
                  @change="permissionChange(item)"
                />
              </el-checkbox-group>
            </el-card>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="5">
            <el-form-item label="是否启用" prop="status">
              <el-radio-group v-model="form.status" class="status-class">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clickCancel">取 消</el-button>
        <el-button type="primary" @click="clickOk">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},

  data() {
    //这里存放数据
    return {
      // 分页查询添加
      queryInfo: {
        // 页面
        pageNumber: 1,
        // 页数
        pageSize: 7,
        // 关键字
        queryString: null,
      },
      // 表格数据
      tableList: [],
      // 总记录数
      total: 0,
      // 表单标题
      title: null,
      // 是否打开对话框
      open: false,
      // 加载效果
      loading: false,
      // 表单数据
      form: {
        status: true,
      },
      // 表单校验
      rules: {
        label: [
          { required: true, message: "请输入角色标签", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "角色标签的长度为1~50之间",
            trigger: "blur",
          },
        ],
        code: [
          { required: true, message: "请输入角色标签值", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "角色标签值的长度为1~20之间",
            trigger: "blur",
          },
        ],
      },
      // 后端获取菜单列表
      menuList: [],
      // 选择的菜单
      checkMenus: [],
      // 后端获取权限列表
      permissions: [],
      // 选中的权限的label(控制选中样式)
      checkPermissions: [],
      // 选中的权限(控制返回结果)
      checkPermis: [],
    };
  },

  //方法集合
  methods: {
    // 查询所有的菜单信息
    findMenusAndPermissions() {
      this.$ajax.get("/menu/findParent").then((res) => {
        this.menuList = res.data;
        // 改造菜单列表
        this.menuList.filter((item) => {
          // 给父级菜单添加disabled属性
          item.disabled = !item.status;
          if (item.children && item.children.length > 0) {
            item.children.filter((i) => {
              // 给子级菜单添加disabled属性
              i.disabled = !i.status;
            });
          }
          return true;
        });
      });
      this.$ajax.get("/permission/findAll").then((res) => {
        this.permissions = res.data;
      });
    },

    // 发送axios进行异步通讯 获取分页数据
    findPage() {
      this.loading = true;
      // 发送axios进行异步通讯 获取分页数据
      this.$ajax.post("/role/findPage", this.queryInfo).then((res) => {
        this.loading = false;
        this.tableList = res.rows;
        this.total = res.total;
      });
    },

    querySearch(value) {
      this.queryInfo.queryString = value;
      this.findPage();
    },
    
    // 打开新增对话框
    insert() {
      //将整个表单进行重置
      this.form = {};
      this.form.status = true;
      this.title = "新增角色";
      this.open = true;
    },

    // 打开修改对话框
    update(row) {
      console.log(row);
      this.checkMenus = [];
      this.checkPermissions = [];

      // 将当前行的数据显示到打开的对话框
      this.form = row;
      this.title = "修改角色";
      row.menus.forEach((item) => {
        this.checkMenus.push(item);
        if (item.children && item.children.length > 0) {
          item.children.forEach((i) => {
            this.checkMenus.push(i);
          });
        }
      });
      row.permissions.forEach((item) => {
        this.checkPermissions.push(item.label);
        this.checkPermis.push(item);
      });

      // 添加异步方法
      this.$nextTick(() => {
        this.$refs.tree.setCheckedNodes(this.checkMenus);
      });
      this.open = true;
    },

    /* 页码改变事件 */
    handlePageNumber(newPageNumber) {
      // 将点击页码后的新数据赋值给分页参数
      this.queryInfo.pageNumber = newPageNumber;
      // 调用分页方法，获取新页码对应的数据
      this.findPage();
    },

    /* 页面显示总条数改变事件 */
    handlePageSize(newPageSize) {
      // 将点击每页几条的新数据赋值给分页参数
      this.queryInfo.pageSize = newPageSize;
      // 调用分页方法，获取新的页面总条数
      this.findPage();
    },

    /* 删除角色信息 */
    deleteById(id) {
      this.$confirm(
        "您的操作将永久删除编号为{" + id + "} 的数据, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          // 调用后端删除角色接口
          this.$ajax.delete(`/role/delete/${id}`).then((res) => {
            // 显示信息
            this.$message.success(res.message);
            // 跳转到第一页数据
            this.queryInfo.pageNumber = 1;
            // 重新查询数据
            this.findPage();
          });
        })
        .catch(() => {});
    },

    /* 关闭对话框的事件 */
    dialogClose() {
      // 重置权限选择框
      this.checkPermissions = [];
      // 重置菜单选择框
      this.checkMenus = [];
      this.$refs.tree.setCheckedKeys([]);
      //将整个表单进行重置，并移除校验效果
      this.$refs.form.resetFields();
      // 点击x号后需重置页面
      this.findPage();
    },

    /* 点击取消 */
    clickCancel() {
      // 重置权限选择框
      this.checkPermissions = [];
      // 重置菜单选择框
      this.checkMenus = [];
      this.$refs.tree.setCheckedKeys([]);
      this.form = {};
      this.open = false;
      // 点击取消后需重置页面
      this.findPage();
    },

    /* 点击确定 */
    clickOk() {
      // 进行表单校验
      this.$refs.form.validate((valid) => {
        //校验不通过
        if (!valid)
          return this.$message.error("表单检验不通过，请检查后提交！");
        //校验通过 判断是否是新增(新增时不带id，修改时带id)
        this.form.menus = this.checkMenus;
        this.form.permissions = this.checkPermis;
        if (this.form.id === undefined || this.form.id === null) {
          this.$ajax.post("/role/insert", this.form).then((res) => {
            this.$message.success(res.message);
            this.open = false;
            this.findPage();
          });
        } else {
          this.$ajax.put("/role/update", this.form).then((res) => {
            this.$message.success(res.message);
            this.open = false;
            this.findPage();
          });
        }
      });
    },

    /* 改变角色数据的状态 */
    updateStatus(row) {
      this.$ajax.put("/role/update", row).then((res) => {
        this.$message.success("状态更新成功！");
      });
    },

    /* 菜单树形控件 节点值被选中 */
    treeChange(data, check) {
      // 当子节点被选中时关联父节点

      this.checkMenus = [];
      /**
       * getCheckedNodes: 获取tree控件被选中的值的数据
       * 参数1: 是否只获取父节点数据
       * 参数2: 当check-strictly为false的情况下，是否包含父节点数据
       */
      const checks = this.$refs.tree.getCheckedNodes(false, true);
      checks.forEach((item) => {
        this.checkMenus.push(item);
      });
    },

    /** 权限选中事件 */
    permissionChange(item) {
      if (this.checkPermissions.length > this.checkPermis.length) {
        // 当权限值被选中时，将对应的权限数据添加到选中权限数据组中
        this.checkPermis.push(item);
      } else {
        // 当选中权限数据组中多出权限值组的内容时删除
        this.checkPermis = this.checkPermis.filter((i) => {
          return this.checkPermissions.includes(i.label);
        });
      }
    },
  },

  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.findPage();
    this.findMenusAndPermissions();
  },
};
</script>
<style scoped>
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.el-col {
  margin-left: 10px;
  margin-right: 10px;
}
.el-checkbox {
  margin-right: 10px;
  margin-bottom: 10px;
}
</style>
